package controllers;

import java.util.Date;

import models.ApiKey;

import org.codehaus.jackson.node.ObjectNode;

import play.libs.Json;
import play.mvc.Action;
import play.mvc.Http.Context;
import play.mvc.Result;

import com.google.common.base.Joiner;

public class ApiSecure extends Action.Simple {

    @Override
    public Result call(Context ctx) throws Throwable {
        ObjectNode result = Json.newObject();

        // Get parameters (Array)
        String[] keyIdParams = ctx.request().queryString().get("keyId");
        String[] vCodeParams = ctx.request().queryString().get("vCode");

        // Null check
        if (keyIdParams == null || vCodeParams == null) {
            result.put("error", "Null credentials parameters");
            return ok(result);
        }

        // Get parameters
        String keyId = Joiner.on("").join(keyIdParams);
        String vCode = Joiner.on("").join(vCodeParams);

        // Empty check
        if (keyId.isEmpty() || vCode.isEmpty()) {
            result.put("error", "Empty credentials parameters");
            return ok(result);
        }

        ApiKey apiKey = ApiKey.find.where().eq("keyId", keyId).eq("vCode", vCode).findUnique();

        // Credentials check
        if (apiKey == null) {
            result.put("error", "Wrong credentials parameters");
            return ok(result);
        }

        // EndDate check
        if (apiKey.getEndDate().before(new Date())) {
            result.put("error", "ApiKey expired");
            return ok(result);
        }

        ctx.session().put("user", apiKey.getUser().getId().toString());

        return delegate.call(ctx);
    }

}
